﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using WGM_Silverlight.Controls;
using System.Windows.Browser;

namespace WGM_Silverlight
{
    public partial class MasterPage : UserControl
    {
        WGM_Svc.ServiceSoapClient _wgmSvc = new WGM_Silverlight.WGM_Svc.ServiceSoapClient();
        public string MacAddress { get; set; }
        public MasterPage()
        {
            InitializeComponent();
            InitWebService();
            _networksView.RefreshNetworksClick += new MouseButtonEventHandler(_networksView_RefreshNetworksClick);
            _networksView.LogoffClick += new MouseButtonEventHandler(_networksView_LogoffClick);

        }

        private void InitWebService()
        {
            _wgmSvc.GetNetworksCompleted += new EventHandler<WGM_Silverlight.WGM_Svc.GetNetworksCompletedEventArgs>(_wgmSvc_GetNetworksCompleted);
            _wgmSvc.CreateUserCompleted += new EventHandler<WGM_Silverlight.WGM_Svc.CreateUserCompletedEventArgs>(_wgmSvc_CreateUserCompleted);
            _wgmSvc.JoinNetworkCompleted += new EventHandler<WGM_Silverlight.WGM_Svc.JoinNetworkCompletedEventArgs>(_wgmSvc_JoinNetworkCompleted);
            _wgmSvc.ConvertUserImagesCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(_wgmSvc_ConvertUserImagesCompleted);
        }

        void _wgmSvc_ConvertUserImagesCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {

            }
        }
        void _wgmSvc_JoinNetworkCompleted(object sender, WGM_Silverlight.WGM_Svc.JoinNetworkCompletedEventArgs e)
        {
            _networksView.IsEnabled = true;
            if (e.Error == null)
            {
                NetworkInfo ni = e.UserState as NetworkInfo;
                ni.NetworkStatusMessage = e.message;
                if (e.Result != null)
                {
                    ni.NetworkStatusMessage = "Building contact list...";
                    _mainView.NetworkName = ni.NetworkName;
                    _mainView.NetworkDescription = ni.NetworkDescription;
                    _mainView.SetInformation(_wgmSvc, _loginView.Username, _loginView.Password, ni.NetworkName, ni.NetworkPassword, MacAddress);
                    _mainTab.IsSelected = true;
                }
            }
        }

        void _wgmSvc_CreateUserCompleted(object sender, WGM_Silverlight.WGM_Svc.CreateUserCompletedEventArgs e)
        {
            throw new NotImplementedException();
        }
        void _wgmSvc_GetNetworksCompleted(object sender, WGM_Silverlight.WGM_Svc.GetNetworksCompletedEventArgs e)
        {
            _loginView.IsEnabled = true;
            if (e.Error == null)
            {
                if (e.Result != null)
                {
                    if (_loginView.RememberLogin)
                    {
                        SetCookie("wgm_remember_login", "true");
                        SetCookie("wgm_username", _loginView.Username);
                        SetCookie("wgm_password", _loginView.Password);
                    }
                    _loginView.LoginMessage = e.message;
                    foreach (var network in e.Result)
                    {
                        NetworkInfo ni = new NetworkInfo();
                        ni.NetworkName = network.NetworkName;
                        ni.NetworkDescription = network.NetwordDescription;
                        ni.NetworkCreator = network.NetworkCreatedBy;
                        ni.NetworkMemberCount = network.NetworkMembersCount;
                        if (network.IsRequesterAMember || !network.IsPasswordProtected)
                        {
                            ni.NetworkPasswordPromptVisibility = ni.NetworkPasswordVisibility = Visibility.Collapsed;
                            ni.NetworkColour = Color.FromArgb(255, 0, 255, 100);
                        }
                        else if (!network.IsRequesterAMember && !network.IsPasswordProtected)
                        {
                            ni.NetworkPasswordPromptVisibility = ni.NetworkPasswordVisibility = Visibility.Collapsed;
                            ni.NetworkColour = Colors.Yellow;
                        }
                        else
                        {
                            ni.NetworkPasswordPromptVisibility = ni.NetworkPasswordVisibility = Visibility.Visible;
                            ni.NetworkColour = Colors.Red;

                        }
                        ni.EnterNetworkClick += new MouseButtonEventHandler(ni_EnterNetworkClick);
                        ni.PasswordKeyUp += new KeyEventHandler(ni_PasswordKeyUp);
                        _networksView.AddNetwork(ni);

                    }
                    _networksView.Username = _loginView.Username;
                    _networksTab.IsSelected = true;
                    
                }
                else
                { 
                    _loginView.LoginMessage = e.message;
                }
            }
        }

        void _networksView_LogoffClick(object sender, MouseButtonEventArgs e)
        {
            _loginView.LoginMessage = "Welcome to WGM";
            _networksView.ClearNetworks();
            _loginTab.IsSelected = true;
        }

        void _networksView_RefreshNetworksClick(object sender, MouseButtonEventArgs e)
        {
            RefreshNetworks();
        }

        private void RefreshNetworks()
        {
            _networksView.ClearNetworks();

            _wgmSvc.GetNetworksAsync(_loginView.Username, _loginView.Password);
        }

        void ni_PasswordKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                NetworkInfo ni = (sender as PasswordBox).Tag as NetworkInfo;
                ni.NetworkStatusMessage = "Joining Network";
                _networksView.IsEnabled = false;
                _wgmSvc.JoinNetworkAsync(_loginView.Username, _loginView.Password, ni.NetworkName, ni.NetworkPassword, MacAddress, ni);

            }
        }

        void ni_EnterNetworkClick(object sender, MouseButtonEventArgs e)
        {
            NetworkInfo ni = (sender as CategoryButton).Tag as NetworkInfo;
            ni.NetworkStatusMessage = "Joining Network";
            _networksView.IsEnabled = false;
            _wgmSvc.JoinNetworkAsync(_loginView.Username, _loginView.Password, ni.NetworkName, ni.NetworkPassword, MacAddress, ni);
        }

        void _wgmSvc_GetOnlineUserNamesCompleted(object sender, WGM_Silverlight.WGM_Svc.GetOnlineUserNamesCompletedEventArgs e)
        {
            
        }
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            MacAddress = "wgm_website" + DateTime.Now.ToString("yyMMdd:HHmmss");
            HtmlPage.Window.Eval(string.Format("document.title=\"{0}\"", "WGM Beta"));
            if (GetCookie("wgm_remember_login") != null && GetCookie("wgm_remember_login") == "true")
            {                
                _loginView.RememberLogin = true;
                _loginView.Username = GetCookie("wgm_username");
                _loginView.Password = GetCookie("wgm_password");
            }
            
        }



        private void OnLoginClick(object sender, MouseButtonEventArgs e)
        {
            _loginView.LoginMessage = "Logging in, please wait...";
            _loginView.IsEnabled = false;
            _loginView.ClearAnimations();
            _wgmSvc.GetNetworksAsync(_loginView.Username, _loginView.Password);
        }

        private void OnCreateAccountClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                _loginView.LoginMessage = "Logging in, please wait...";
                _loginView.IsEnabled = false;
                _wgmSvc.GetNetworksAsync(_loginView.Username, _loginView.Password);
            }
        }
        private void SetCookie(string key, string value)
        {
            // Expire in 7 days
            DateTime expireDate = DateTime.Now + TimeSpan.FromDays(7);
            string newCookie = key + "=" + value + ";expires=" + expireDate.ToString("R");
            HtmlPage.Document.SetProperty("cookie", newCookie);
        }
        private string GetCookie(string key)
        {
            string[] cookies = HtmlPage.Document.Cookies.Split(';');
            foreach (string cookie in cookies)
            {
                string[] keyValue = cookie.Split('=');
                if (keyValue.Length == 2)
                {
                    if (keyValue[0].ToString().Trim() == key)
                        return keyValue[1];
                }
            }
            return null;
        }

        private void OnBackToLobby(object sender, MouseButtonEventArgs e)
        {
            _mainView.ShutDown();
            _networksTab.IsSelected = true;
            RefreshNetworks();
        }
    }
}
